﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ContractorTimesheet.DataModel;
using ContractorTimesheet.Infrastructure;
using ContractorTimesheet.Models;
using ContractorTimesheet.Repository;
using SimpleCrypto;

namespace ContractorTimesheet.Controllers
{
    public class UsersController : BaseController
    {
        private UserRepository repository = new UserRepository();

        public ActionResult Index()
        {
            var model = new UserEditorModel();

            model.UsersInfo.AddRange(UserInfo.CreateUsersInfo(repository.GetAllUsers()));

            return View(model.SortByName());
        }

        public ActionResult AddUser(UserEditorModel model)
        {
            PBKDF2 crypto = new PBKDF2();
            string password = crypto.Compute(ConfigurationManager.AppSettings.Get("DefaultPassword"));
            string passwordSalt = crypto.Salt;

            User newUser = new User(model.NewFirstname, model.NewLastname, model.NewEmail, model.NewPO, model.NewBadgeNo, false, model.NewIsActive, password, passwordSalt);

            repository.Add(newUser);

            model.UsersInfo.Add(new UserInfo(newUser));

            model.ResetNewUser();

            return Json(model.SortByName());
        }

        public ActionResult DeleteUser(UserEditorModel model, int index)
        {
            UserInfo userInfo = model.UsersInfo[index];

            repository.DeleteAsync(userInfo.Id);

            model.UsersInfo.Remove(userInfo);

            return Json(model);
        }

    }
}